package com.lykj.llw.box.ui.activity

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.dinuscxj.itemdecoration.LinearDividerItemDecoration
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.app.BaseApplication
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.R
import com.lykj.llw.box.adapter.ChooseRoleAdapter
import com.lykj.llw.box.adapter.ChooseServerAdapter
import com.lykj.llw.box.data.bean.response.ChooseRoleResponse
import com.lykj.llw.box.data.bean.response.ChooseServerResponse
import com.lykj.llw.box.data.bean.response.VipGiftBagDetailResponse
import com.lykj.llw.box.databinding.ActVipGiftBagBinding
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody

/**
 * ================================================
 * 会员礼包申请页面
 * ================================================
 *
 * @author gosha
 * @date 2023/12/25-13:40
 */
class VIPGiftBagActivity : BaseActivity() {
    lateinit var binding: ActVipGiftBagBinding

    private var gid = 0

    private val mServerAdapter = ChooseServerAdapter()
    private val mServerData = ArrayList<ChooseServerResponse.DataDTO>()
    private var mServerSelectId = ""

    private val mRoleAdapter = ChooseRoleAdapter()
    private val mRoleData = ArrayList<ChooseRoleResponse.DataDTO>()
    private var mRoleSelectId = ""

    private var mCardId = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActVipGiftBagBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initUI()
        initData()
        setListener()
    }

    override fun initUI() {
        binding.titleBar.tvTitle.text = "礼包详情"
        binding.titleBar.tvRightOption.visibility = View.GONE

        initServerRCV()
        initRoleRCV()
    }

    private fun initServerRCV() {
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.rcvServer.layoutManager = linearLayoutManager
        binding.rcvServer.setHasFixedSize(true)

        val dividerItemDecoration = LinearDividerItemDecoration(
            this, LinearDividerItemDecoration.LINEAR_DIVIDER_VERTICAL
        )
        dividerItemDecoration.setDivider(
            resources.getDrawable(
                R.drawable.divider_5dp, resources.newTheme()
            )
        )
        binding.rcvServer.addItemDecoration(dividerItemDecoration, 0)
        mServerAdapter.data = mServerData
        mServerAdapter.setOnItemClickListener { adapter, view, position ->
            mServerSelectId = mServerData[position].serviceId

            //隐藏列表
            binding.tvChooseServer.text = "${mServerData[position].serviceName}"
            binding.rcvServer.visibility = View.GONE
            binding.ivServerChoose.setImageResource(R.mipmap.ic_pull_down)
        }
        binding.rcvServer.adapter = mServerAdapter
    }

    private fun initRoleRCV() {
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.rcvRole.layoutManager = linearLayoutManager
        binding.rcvRole.setHasFixedSize(true)

        val dividerItemDecoration = LinearDividerItemDecoration(
            this, LinearDividerItemDecoration.LINEAR_DIVIDER_VERTICAL
        )
        dividerItemDecoration.setDivider(
            resources.getDrawable(
                R.drawable.divider_5dp, resources.newTheme()
            )
        )
        binding.rcvRole.addItemDecoration(dividerItemDecoration, 0)
        mRoleAdapter.data = mRoleData
        mRoleAdapter.setOnItemClickListener { adapter, view, position ->
            mRoleSelectId = mRoleData[position].roleId

            //隐藏列表
            binding.tvChooseRole.setText("${mRoleData[position].roleName}")
            binding.rcvRole.visibility = View.GONE
            binding.ivRoleChoose.setImageResource(R.mipmap.ic_pull_down)
        }
        binding.rcvRole.adapter = mRoleAdapter
    }

    override fun onResume() {
        super.onResume()

        ImmersionBar.with(this)
            .transparentBar()
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()
    }

    //获取vip会员礼包详情
    private fun obtainVipGiftBagDetail() {
        RetrofitManager.instance?.obtainVipGiftBagDetail("$gid",
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this@VIPGiftBagActivity, d)
                }

                override fun specificHandle(responseBody: String) {
                    val bean =
                        GsonUtils.fromJson(responseBody, VipGiftBagDetailResponse::class.java)

                    if (null != bean.data) {
                        mCardId = bean.data.vipCardId

                        val subject =
                            bean.data.cardContent
                                .replace("&nbsp", "").replace("&lt;", "<").replace("&gt;", ">")
                                .replace("&amp;", "&").replace("&cent;", "¢")
                                .replace("&pound;", "£")
                                .replace("&yen;", "¥").replace("&euro;", "€").replace("&sect;", "§")
                                .replace("&copy;", "©").replace("&reg;", "®")
                                .replace("&trade;", "™")

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            binding.tvContent.text =
                                Html.fromHtml(subject, Html.FROM_HTML_MODE_LEGACY)
                        } else {
                            binding.tvContent.text = Html.fromHtml(subject)
                        }

                        if (bean.data.status == 9 || bean.data.status == -1) {
                            binding.tvBtnApply.visibility = View.VISIBLE
                        } else {
                            //设置区服,角色
                            binding.tvChooseServer.text = "${bean.data.serverName}"
                            binding.tvChooseRole.text = "${bean.data.roleName}"
                            mServerSelectId = "${bean.data.serverId}"
                            binding.tvBtnApply.visibility = View.INVISIBLE
                            binding.ivServerChoose.isEnabled = false
                            binding.ivServerDelete.isEnabled = false
                            binding.ivRoleChoose.isEnabled = false
                            binding.ivRoleDelete.isEnabled = false

                            binding.ivServerDelete.visibility = View.GONE
                            binding.ivServerChoose.visibility = View.GONE
                            binding.ivRoleDelete.visibility = View.GONE
                            binding.ivRoleChoose.visibility = View.GONE
                        }
                    } else {
                        ToastUtils.showShort(this@VIPGiftBagActivity, "该会员暂无会员礼包")
                    }
                }

                override fun handleException(ret: String, msg: String?) {
                    msg?.let {
                        ToastUtils.showShort(this@VIPGiftBagActivity, it)
                    }
                }
            })
    }

    //提交申请vip礼包
    private fun applyVipGiftBag() {
        clearBodyParam()
        initBodyParam()
        bodyParams["gameId"] = "$gid"
        bodyParams["roleName"] = "${binding.tvChooseRole.text}"
        bodyParams["serverId"] = "$mServerSelectId"
        bodyParams["vipCardId"] = mCardId
        RetrofitManager.instance?.applyVipGiftBag(
            bodyParams,
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this@VIPGiftBagActivity, d)
                }

                override fun specificHandle(responseBody: String) {
                    ToastUtils.showShort(this@VIPGiftBagActivity, "申请提交成功")

                    binding.tvBtnApply.visibility = View.GONE
                }

                override fun handleException(ret: String, msg: String?) {
                    msg?.let {
                        ToastUtils.showShort(this@VIPGiftBagActivity, it)
                    }
                }

            })
    }

    //获取下拉区服
    private fun obtainChooseServer() {
        RetrofitManager.instance?.obtainChooseServer(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@VIPGiftBagActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(
                    responseBody, ChooseServerResponse::class.java
                )

                mServerData.clear()
                if (bean.data.size > 0) {
                    binding.rcvServer.visibility = View.VISIBLE
                    mServerData.addAll(bean.data)

                    binding.ivServerChoose.setImageResource(R.mipmap.ic_pull_up)
                } else {
                    binding.rcvServer.visibility = View.GONE
                    binding.ivServerChoose.setImageResource(R.mipmap.ic_pull_down)
                    ToastUtils.showShort(this@VIPGiftBagActivity, "没有相关区服信息")
                }

                mServerAdapter.notifyDataSetChanged()
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@VIPGiftBagActivity, it)
                }
            }

        }, "$gid")
    }

    //获取下拉角色
    private fun obtainChooseRole() {
        RetrofitManager.instance?.obtainChooseRole(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@VIPGiftBagActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(
                    responseBody, ChooseRoleResponse::class.java
                )

                mRoleData.clear()
                if (bean.data.size > 0) {
                    binding.rcvRole.visibility = View.VISIBLE
                    mRoleData.addAll(bean.data)

                    binding.ivRoleChoose.setImageResource(R.mipmap.ic_pull_up)
                } else {
                    binding.rcvRole.visibility = View.GONE
                    binding.ivRoleChoose.setImageResource(R.mipmap.ic_pull_down)
                    ToastUtils.showShort(this@VIPGiftBagActivity, "没有相关角色信息")
                }

                mRoleAdapter.notifyDataSetChanged()
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@VIPGiftBagActivity, it)
                }
            }

        }, "$gid", "${mServerSelectId}")
    }

    override fun initData() {
        gid = intent.getIntExtra("gid", 0)
        obtainVipGiftBagDetail()
    }

    override fun setListener() {
        binding.titleBar.ivBack.clickWithTrigger {
            finish()
        }

        binding.tvBtnApply.clickWithTrigger(220) {
            if (binding.tvChooseServer.text.isNullOrBlank()) {
                ToastUtils.showShort(this, "请先选择区服")
                return@clickWithTrigger
            }

            if (binding.tvChooseRole.text.isNullOrBlank()) {
                ToastUtils.showShort(this, "请先选择角色")
                return@clickWithTrigger
            }

            applyVipGiftBag()
        }

        binding.root.clickWithTrigger(1) {
//            mIsSet = false
            //隐藏列表
            binding.rcvServer.visibility = View.GONE
            binding.ivServerChoose.setImageResource(R.mipmap.ic_pull_down)

            binding.rcvRole.visibility = View.GONE
            binding.ivRoleChoose.setImageResource(R.mipmap.ic_pull_down)
        }


        binding.ivServerChoose.clickWithTrigger(1) {
            if (null == BaseApplication.instance?.getUserInfo()) {
                startActivity(Intent(this, MobileLoginActivity::class.java))
            } else {
                obtainChooseServer()
            }
        }

        binding.ivServerDelete.clickWithTrigger(1) {
            KeyboardUtils.hideSoftInput(this)
            binding.tvChooseServer.text = ""
        }

        binding.ivRoleChoose.clickWithTrigger(1) {
            if (binding.tvChooseServer.text.isNullOrBlank()) {
                ToastUtils.showShort(this@VIPGiftBagActivity, "请先选择对应区服")
                return@clickWithTrigger
            }
            obtainChooseRole()
        }

        binding.ivRoleDelete.clickWithTrigger(1) {
            KeyboardUtils.hideSoftInput(this)
            binding.tvChooseRole.text = ""
        }
    }

    override fun onDestroy() {
        removeDisposables(this)
        super.onDestroy()
    }
}